var ws = require("nodejs-websocket")
const TYPE_ENTER=0
const TYPE_MSG=1
const TYPE_CLOSE=2

var server = ws.createServer(function (connection) {
    
    connection.on("text", function (data) {
        const info=JSON.parse(data)
        if(info.type===TYPE_ENTER){
            connection.username=info.username	// 每个连接有个用户名
            const msg=connection.username+'进入聊天室'  
            broadcast(JSON.stringify({  		// 广播信息
                msg,
                type:TYPE_ENTER
            }))
        }else if(info.type===TYPE_MSG){
            const msg=connection.username+'：'+info.msg
            broadcast(JSON.stringify({
                msg,
                type:TYPE_MSG,
                color:info.color
            }))
        }
    })

    connection.on("close", function (code, reason) {
        const msg=connection.username+'离开聊天室'
        broadcast(JSON.stringify({
            msg,
            type:TYPE_CLOSE
        }))
    })
    
    connection.on('error',(err)=>{
        console.log('异常：',err)
    })
}).listen(8001)

function broadcast(msg){
    server.connections.forEach(item=>{
        item.send(msg)
    })
}